package vn.fpt.fsoft.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import vn.fpt.fsoft.dao.*;
import vn.fpt.fsoft.entity.*;

/*
 * Class TrustRegionController
 *
 * Version 1.0
 *
 * 25-August-2014
 *
 * Modification Logs:
 * DATE                 AUTHOR              DESCRIPTION
 * --------------------------------------------------------
 * 25-August-2014       XuanTuan            Create Class TrustRegionController
 * 2-September-2014     XuanTuan            Repair doPost method
 * 2-September-2014     XuanTuan            add listTrustRegion method
 * 2-September-2014     XuanTuan            add markActiveTrustRegion method
 * 2-September-2014     XuanTuan            add markInActive method
 */
/**
 * Servlet implementation class TrustRegionController
 */
@WebServlet("/TrustRegionController")
public class TrustRegionController extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private TrustRegionDAO trustRegionDAO=new TrustRegionDAO();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TrustRegionController() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    @SuppressWarnings("unchecked")
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String result = "";
        String action = request.getParameter("action");
        List<Country> listCountry = null;
        TrustRegion trustRegion = new  TrustRegion();
        Country country = new Country();
        
        if (request.getSession().getAttribute("listTrustRegion") != null) {
            request.getSession().removeAttribute("listTrustRegion");
            request.getSession().removeAttribute("currentListTrustRegion");
        }
        if (request.getSession().getAttribute("ListCountry") == null) {
            listCountry = getAllListCountry();
            request.getSession().setAttribute("ListCountry", listCountry);
        } else {
            listCountry = (List<Country>) request.getSession().getAttribute("ListCountry");
        }
        if ("getdata".equals(action)) {
            for (Country tmp : listCountry) {
                result += "<option value=" + tmp.getCountryID() + ">" + tmp.getCountryName() + "</option>";
            }
            response.getWriter().write(result);
        } else if ("add".equals(action)) {
           country.setCountryID(Integer.parseInt(request.getParameter("countryid")));
           country.setCountryName(request.getParameter("countryname"));
           trustRegion.setName(request.getParameter("name"));
           trustRegion.setCountry(country);
           trustRegion.setDescript(request.getParameter("description"));
           trustRegion.setActive(true);
           boolean tmp = addTrustRegion(trustRegion);
           if (tmp) {
               response.getWriter().write("Success!!!");
           } else {
               response.getWriter().write("Fail!!!! Trust Region is existed");
           }
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String action = request.getParameter("action");
        
        if (action != null) {
            if ("active".equals(action)) {
                markActiveTrustRegion(request,response);
                listTrustRegion(request, response);
                
            } else if ("listTrustRegion".equals(action)) {
                listTrustRegion(request, response);
            } else if ("getData".equals(action)) {
                Integer regionID = Integer.parseInt(request.getParameter("regionID"));
                TrustRegion td = getTrustRegionByKey(regionID);
                JsonObject jsonObj = new JsonObject();
                jsonObj.addProperty("regionID", td.getTrustRegionID());
                jsonObj.addProperty("Name", td.getName());
                jsonObj.addProperty("Descript", td.getDescript());
                jsonObj.addProperty("CountryName", td.getCountry().getCountryName());
                jsonObj.addProperty("active", td.isActive());
                response.getWriter().write(String.valueOf(jsonObj));
            } else if ("amendTrustRegion".equals(action)) {
                TrustRegion trustRegion = new  TrustRegion();
                Country country = new Country();
                country.setCountryID(Integer.parseInt(request.getParameter("countryid")));
                country.setCountryName(request.getParameter("countryname"));
                trustRegion.setTrustRegionID(Integer.parseInt(request.getParameter("regionID")));
                trustRegion.setName(request.getParameter("name"));
                trustRegion.setCountry(country);
                trustRegion.setDescript(request.getParameter("description"));
                trustRegion.setActive(true);
                boolean tmp = amendTrustRegion(trustRegion);
                if (tmp) {
                    request.getSession().removeAttribute("listTrustRegion");
                    request.getSession().removeAttribute("currentListTrustRegion");
                    response.getWriter().write("Success!!!");
                } else {
                    response.getWriter().write("Fail!!!! Trust Region is existed");
                }
            } else if ("markInActive".equals(action)) {
                TrustRegion trustRegion = new TrustRegion();
                trustRegion = getTrustRegionByKey(Integer.parseInt(request.getParameter("regionID")));
                if (markInActive(trustRegion)) {
                    request.getSession().removeAttribute("listTrustRegion");
                    request.getSession().removeAttribute("currentListTrustRegion");
                    response.getWriter().write("Mark In-active seccess!!!");
                } else {
                    response.getWriter().write("Mark In-active fail!!!");
                }
            }
        }
        
    }
    
    /**
     * @param request
     * @param response
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    private void listTrustRegion(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        boolean checked =Boolean.parseBoolean(request.getParameter("checked"));
        String idClick = request.getParameter("idclick");
        List<TrustRegion> listTrustRegion = new ArrayList<TrustRegion>();
        
        if (request.getSession().getAttribute("listTrustRegion") == null) {
            listTrustRegion = getAllTrustRegion();
            request.getSession().setAttribute("listTrustRegion", listTrustRegion);
            request.getSession().setAttribute("currentListTrustRegion", listTrustRegion);
        } else {
            listTrustRegion = (List<TrustRegion>) request.getSession().getAttribute("listTrustRegion");
            request.getSession().setAttribute("currentListTrustRegion", listTrustRegion);
        }
        
        if (idClick != null) {
            // if the request is filter
            listTrustRegion = filterByName(idClick, listTrustRegion);
            request.getSession().setAttribute("currentListTrustRegion", listTrustRegion);
            // get active user
            if (!checked) {
                listTrustRegion = getAllTrustRegionIsActive(listTrustRegion);
            }
        } else {
            // if the request is show in-active/active user
            listTrustRegion = (List<TrustRegion>) request.getSession().getAttribute("currentListTrustRegion");
            if (!checked) {
                listTrustRegion = getAllTrustRegionIsActive(listTrustRegion);
            }
        }
        
        if (listTrustRegion != null) {
            String json = ConvertListToJson(listTrustRegion);
            response.getWriter().write(json);
        }
        
    }
    
    /**
     * @param request
     * @param response
     * @throws IOException
     */
    private void markActiveTrustRegion(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        int trustRegionID =Integer.parseInt(request.getParameter("trustregionid"));
        TrustRegion trustRegion = new TrustRegion();
        trustRegion = getTrustRegionByKey(trustRegionID);
        if (markActive(trustRegion)) {
            request.getSession().removeAttribute("listTrustRegion");
            request.getSession().removeAttribute("currentListTrustRegion");
        }
        
    }
    
    private String ConvertListToJson(List<TrustRegion> list) {
        JsonObject responseDetailJson = new JsonObject();
        JsonObject jsonObject;
        JsonArray jsonArray = new JsonArray();
        
        for(TrustRegion tmp:list) {
            jsonObject = new JsonObject();
            jsonObject.addProperty("TrustRegionID", tmp.getTrustRegionID());
            jsonObject.addProperty("Descript", tmp.getDescript());
            jsonObject.addProperty("Name", tmp.getName());
            jsonObject.addProperty("CountryName", tmp.getCountry().getCountryName());
            jsonObject.addProperty("IsActive", tmp.isActive());
            jsonArray.add(jsonObject);
        }
        responseDetailJson.add("TrustRegion", jsonArray);
        return String.valueOf(responseDetailJson);
    }
    /**
     * @param trustRegion
     * @return
     */
    private boolean isValidate(TrustRegion trustRegion) {
        List<TrustRegion> list = getAllTrustRegion();
        for (TrustRegion tmp : list) {
            if (trustRegion.getName().equals(tmp.getName())) {
               return false; 
            }
        }
        return true;
    }
    
    private boolean addTrustRegion (TrustRegion trustRegion) {
        
        if (!isValidate(trustRegion))
            return false;
        return trustRegionDAO.addTrustRegion(trustRegion);
    }
    
    private boolean amendTrustRegion (TrustRegion trustRegion) {
        return trustRegionDAO.amendTrustRegion(trustRegion);
    }
    
    /**
     * @return
     */
    private List<Country> getAllListCountry() {
        CountryDAO countryDAO = new CountryDAO();
        
        return countryDAO.getAllCountry();
    }
    
    /**
     * @return
     */
    private List<TrustRegion> getAllTrustRegion() {
        return trustRegionDAO.getAllTrustRegion();
    }
    
    /**
     * @param trustRegionID
     * @return
     */
    private TrustRegion getTrustRegionByKey(int trustRegionID) {
        return trustRegionDAO.getTrustRegionByKey(trustRegionID);
    }
    
    /**
     * @param trustRegion
     * @return
     */
    private boolean markActive (TrustRegion trustRegion) {
        trustRegion.setActive(true);
        return amendTrustRegion(trustRegion);
    }
    
    /**
     * @param trustRegion
     * @return
     */
    private boolean markInActive (TrustRegion trustRegion) {
        trustRegion.setActive(false);
        return amendTrustRegion(trustRegion);
    }
    
    /**
     * @param list
     * @return
     */
    private List<TrustRegion> getAllTrustRegionIsActive(List<TrustRegion> list) {
        List<TrustRegion> listActive = new ArrayList<TrustRegion>();
        for(TrustRegion tmp:list) {
            if(tmp.isActive()) {
                listActive.add(tmp);
            }
        }
        return listActive;
    }
    
    /**
     * @param key
     * @param list
     * @return
     */
    private List<TrustRegion> filterByName(String key, List<TrustRegion> list) {
        List<TrustRegion> listTmp = new ArrayList<TrustRegion>();
        char letter;
        
        if ("all".equals(key)) {
           return list; 
        } else if ("digital".equals(key)) {
            for (TrustRegion tmp : list) {
                if(Character.isDigit(tmp.getName().charAt(0))) {
                    listTmp.add(tmp);
                }
            }
        } else if ("ae".equals(key)) {
            for (TrustRegion tmp : list) {
                letter = Character.toLowerCase(tmp.getName().charAt(0));
                if(('a' <= letter) &&  (letter <= 'e')) {
                    listTmp.add(tmp);
                }
            }
        } else if ("fj".equals(key)) {
            for (TrustRegion tmp : list) {
                letter = Character.toLowerCase(tmp.getName().charAt(0));
                if(('f' <= letter) &&  (letter <= 'j')) {
                    listTmp.add(tmp);
                }
            }
        } else if ("kn".equals(key)) {
            for (TrustRegion tmp : list) {
                letter = Character.toLowerCase(tmp.getName().charAt(0));
                if(('k' <= letter) &&  (letter <= 'n')) {
                    listTmp.add(tmp);
                }
            }
        } else if ("or".equals(key)) {
            for (TrustRegion tmp : list) {
                letter = Character.toLowerCase(tmp.getName().charAt(0));
                if(('o' <= letter) &&  (letter <= 'r')) {
                    listTmp.add(tmp);
                }
            }
        } else if ("sv".equals(key)) {
            for (TrustRegion tmp : list) {
                letter = Character.toLowerCase(tmp.getName().charAt(0));
                if(('s' <= letter) &&  (letter <= 'v')) {
                    listTmp.add(tmp);
                }
            }
        } else if ("wz".equals(key)) {
            for (TrustRegion tmp : list) {
                letter = Character.toLowerCase(tmp.getName().charAt(0));
                if(('w' <= letter) &&  (letter <= 'z')) {
                    listTmp.add(tmp);
                }
            }
        }
        return listTmp;
    }

}
